package com.platform.os.filter;

import java.io.IOException;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.platform.os.bo.AccessBo;
import com.platform.pojo.AccessRecord;
import com.platform.pojo.ResInfo;
import com.platform.pojo.UserInfo;
import com.platform.res.bo.ResBo;
import com.platform.user.bo.UserBo;

//全局编码过滤器
public class URLCharacterEncoding implements Filter {

	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		req.setCharacterEncoding("utf-8");
		res.setCharacterEncoding("utf-8");

		HttpSession session = ((HttpServletRequest)req).getSession();
		
		if(session.getAttribute("accessRecord") == null) {
			AccessBo accessBo = AccessBo.getInstance();
			//获得请求的IP
			String clientIp = req.getRemoteAddr();
			if(clientIp != null && !clientIp.equals("")) {
				AccessRecord accessRecord = accessBo.getAccessRecord(clientIp);
				if(accessRecord == null) {
					//访问记录为空，则插入记录
					accessRecord = new AccessRecord();
					accessRecord.setIp(clientIp);
					accessRecord.setAccessTime(new Date());
					accessBo.addAccessRecord(accessRecord);
				}
				session.setAttribute("accessRecord", accessRecord);
			}
			Long accessCount;	//今日访问总数
			Long resCount;		//资源总数
			Long userCount;		//注册用户总数
			UserInfo daUser;	//共享达人
			ResInfo faRes;		//最热门资源
			if(session.getAttribute("accessCount") == null) {
				//今日访问总数
				accessCount = accessBo.countAccessRecord();
				session.setAttribute("accessCount", accessCount);
			}
			if(session.getAttribute("resCount") == null) {
				//资源总数
				resCount = ResBo.getInstance().getResInfoCount();
				session.setAttribute("resCount", resCount);
			}
			if(session.getAttribute("userCount") == null) {
				//已注册用户数
				userCount = UserBo.getInstance().countUser();
				session.setAttribute("userCount", userCount);
			}
	
			if(session.getAttribute("daUser") == null) {
				//资源共享达人
				daUser = UserBo.getInstance().getDaUser();
				session.setAttribute("daUser", daUser);
			}
	
			if(session.getAttribute("faRes") == null) {
				//最热门资源
				faRes = ResBo.getInstance().getFaRes();
				session.setAttribute("faRes", faRes);
			}
		}
		chain.doFilter(req, res);
	}

	public void init(FilterConfig arg0) throws ServletException {
	}

}
